package org.xt.module.api;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Lang;
import org.nutz.lang.random.R;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.xt.constants.Const;
import org.xt.constants.Res;
import org.xt.entity.Permission;
import org.xt.entity.Role;
import org.xt.entity.User;
import org.xt.service.SFISOpService;
import org.xt.service.PermissionService;
import org.xt.service.RoleService;
import org.xt.service.UserService;
@IocBean
@At("/api/user")
public class UserApiModule {
	@Inject
	private Dao dao;
	@Inject
	private UserService userService;
	@Inject
	private PermissionService permissionService;
	@Inject
	private RoleService roleService;
	@Inject
	private SFISOpService httpService;
	
	@At("/list")
	@POST
	@Ok("json")
	public Res list(@Param(value="page", df="1")int page, @Param(value="size", df="10")int size
			, @Param(value="department", df="0")int department, @Param(value="search", df="")String search){
		//Pager pager = dao.createPager(page, size);
		return Res.NEW().code(Res.SUCCESS).msg("获取部门成功").data(userService.finds(page, size, department, search));
	}
	
	@At("/regist")
	@Ok("json")
	public Res regist(@Param("..")User user){
		try{
			user = userService.create(user);
			if(user != null){
				return Res.NEW().code(Res.SUCCESS).msg("工号注册成功").data(user);
			}else{
				return Res.NEW().code(Res.ERROR).msg("工号注册失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			if(e.getMessage().contains("Violation of UNIQUE KEY constraint")){
				return Res.NEW().code(Res.ERROR).msg("此工号已经注册");
			}else{
				return Res.NEW().code(Res.ERROR).msg("工号注册异常: " + e.getMessage());
			}
		}
	}
	
	@At("/login")
	@Ok("json")
	public Res login(@Param("..")User user, HttpSession session){
		try{
			User userDb = dao.fetch(User.class, Cnd.where("no", "=", user.getNo()));
			if(userDb == null){
				return Res.NEW().code(Res.ERROR).msg("该账户不存在，请重新输入");
			}
			String md5Psd  = Lang.md5(user.getPassword() + userDb.getSalt());
			if(userDb.getPassword().equals(md5Psd)){
				//httpService.setCookies();
				session.setAttribute(Const.LOGIN_USER_SIGN, userDb);
				return Res.NEW().code(Res.SUCCESS).msg("登录成功").data(session.getAttribute(Const.LOGIN_USER_SIGN));
			}else{
				return Res.NEW().code(Res.ERROR).msg("用户名或密码错误，请重新输入");
			}
		}catch(Exception e){
			e.printStackTrace();
			if(e.getMessage().contains("Cookie map must not")){
				return Res.NEW().code(Res.ERROR).msg("登录SIFS出现异常");
			}else{
				return Res.NEW().code(Res.ERROR).msg("登录异常: " + e.getMessage());
			}
		}
		
	}
	
	@At("/changePassword")
	@Ok("json")
	public Res changePassword(int id, String oldPassword, String newPassword){
		User user = dao.fetch(User.class, id);
		String md5Psd  = Lang.md5(oldPassword + user.getSalt());
		if(!user.getPassword().equals(md5Psd)){
			return Res.NEW().code(Res.ERROR).msg("旧密码输入错误");
		}
		if(userService.changePassword(id, newPassword)){
			return Res.NEW().code(Res.SUCCESS).msg("密码更改成功");
		}else{
			return Res.NEW().code(Res.ERROR).msg("密码更改失败");
		}
	}
	
	@At("/update")
	@Ok("json")
	public Res update(int id, String no, String username, HttpSession session){
		User user = dao.fetch(User.class, id);
		user.setNo(no);
		user.setUsername(username);
		if(dao.update(user) > 0){
			session.setAttribute(Const.LOGIN_USER_SIGN, user);
			return Res.NEW().code(Res.SUCCESS).msg("职工信息更新成功");
		}else{
			return Res.NEW().code(Res.ERROR).msg("职工信息更新失败");
		}
	}
	@At("/delete")
	@Ok("json")
	public Res delete(int id){
		if(userService.delete(id) > 0){
			return Res.NEW().code(Res.SUCCESS).msg("职工删除成功");
		}else{
			return Res.NEW().code(Res.ERROR).msg("职工删除失败");
		}
	}
	@At("/findRolesNotUser")
	@Ok("json")
	public Res findRolesNotUser(int id, @Param(value="pager", df="1")int pager
			, @Param(value="size", df="30")int size, @Param(value="serach", df="")String serach){
		try{
			QueryResult qr =userService.findRolesNotUser(id, serach, pager, size);
			return Res.NEW().code(Res.SUCCESS).msg("获取OK")
					.data(NutMap.NEW().addv("roles", qr.getList()).addv("pager", qr.getPager()));
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("获取异常: " + e.getMessage());
		}
	}
	@At("/findRolesByUser")
	@Ok("json")
	public Res findRolesByUser(int id){
		try{
			return Res.NEW().code(Res.SUCCESS).msg("获取OK")
					.data(NutMap.NEW().addv("roles", userService.findRolesByUser(id)));
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("获取异常: " + e.getMessage());
		}
	}
	@At("/addUR")
	@Ok("json")
	public Res addUR(int userId, String role){
		try{
			String[] rs = role.split("-");
			int[] rids = new int[rs.length];
			for(int i = 0; i < rs.length; i ++){
				rids[i] = Integer.parseInt(rs[i]);
			}
			return Res.NEW().code(Res.SUCCESS).msg("添加了" + userService.addRole(userId, rids) + "条记录");
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("添加异常: " + e.getMessage());
		}
	}
	@At("/removeUR")
	@Ok("json")
	public Res removeUR(int userId, String role){
		try{
			String[] rs = role.split("-");
			int[] rids = new int[rs.length];
			for(int i = 0; i < rs.length; i ++){
				rids[i] = Integer.parseInt(rs[i]);
			}
			return Res.NEW().code(Res.SUCCESS).msg("删除了" + userService.removeRole(userId, rids) + "条记录");
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("删除异常: " + e.getMessage());
		}
	}
	@At("/permission/list")
	@Ok("json")
	public Res permissionList(@Param("page")int page, @Param("size")int size){
		try{
			Pager pager = dao.createPager(page, size);
			pager.setRecordCount(dao.count(Permission.class, null));
			return Res.NEW().code(Res.SUCCESS).msg("获取权限OK")
					.data(new QueryResult(dao.query(Permission.class, null, pager), pager));
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("获取权限异常: " + e.getMessage());
		}
	}
	
	@At("/permission/add")
	@Ok("json")
	public Res addPermission(@Param("..")Permission permission){
		try{
			permission = permissionService.add(permission);
			if(permission != null){
				return Res.NEW().code(Res.SUCCESS).msg("添加权限成功").data(permission);
			}else{
				return Res.NEW().code(Res.ERROR).msg("添加权限失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("添加权限异常: " + e.getMessage());
		}
	}
	@At("/permission/update")
	@Ok("json")
	public Res updatePermission(@Param("..")Permission permission){
		try{
			permission.setUpdateTime(new Date());
			if(dao.updateIgnoreNull(permission) > 0){
				return Res.NEW().code(Res.SUCCESS).msg("更新权限成功");
			}else{
				return Res.NEW().code(Res.ERROR).msg("更新权限失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("更新权限异常: " + e.getMessage());
		}
	}
	
	@At("/permission/delete")
	@Ok("json")
	public Res deletePermission(int id){
		try{
			int sum = permissionService.delete(id);
			return Res.NEW().code(Res.SUCCESS).msg("删除" + sum + "条权限");
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("删除权限异常: " + e.getMessage());
		}
	}
	@At("/role/list")
	@Ok("json")
	public Res roleList(@Param("page")int page, @Param("size")int size){
		try{
			Pager pager = dao.createPager(page, size);
			pager.setRecordCount(dao.count(Role.class, null));
			return Res.NEW().code(Res.SUCCESS).msg("获取角色OK")
					.data(new QueryResult(dao.query(Role.class, null, pager), pager));
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("获取角色异常: " + e.getMessage());
		}
	}
	
	@At("/role/findPermissionsNotRole")
	@Ok("json")
	public Res findPermissionsNotRole(int id, @Param(value="pager", df="1")int pager
			, @Param(value="size", df="30")int size, @Param(value="serach", df="")String serach){
		try{
			QueryResult qr = roleService.findPermissionsNotRole(id, serach, pager, size);
			return Res.NEW().code(Res.SUCCESS).msg("获取OK")
					.data(NutMap.NEW().addv("permissions", qr.getList()).addv("pager", qr.getPager()));
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("获取异常: " + e.getMessage());
		}
	}
	
	@At("/role/findPermissionsByRole")
	@Ok("json")
	public Res findPermissionsByRole(int id){
		try{
			return Res.NEW().code(Res.SUCCESS).msg("获取OK")
					.data(NutMap.NEW().addv("permissions", roleService.findPermissionsByRole(id)));
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("获取异常: " + e.getMessage());
		}
	}
	
	@At("/role/add")
	@Ok("json")
	public Res addRole(@Param("..")Role role){
		try{
			role = roleService.add(role);
			if(role != null){
				return Res.NEW().code(Res.SUCCESS).msg("添加角色成功").data(role);
			}else{
				return Res.NEW().code(Res.ERROR).msg("添加角色失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("添加角色异常: " + e.getMessage());
		}
	}
	
	@At("/role/addRP")
	@Ok("json")
	public Res addRP(int roleId, String permission){
		try{
			String[] ps = permission.split("-");
			int[] pids = new int[ps.length];
			for(int i = 0; i < ps.length; i ++){
				pids[i] = Integer.parseInt(ps[i]);
			}
			return Res.NEW().code(Res.SUCCESS).msg("添加了" + roleService.addPermission(roleId, pids) + "条记录");
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("添加异常: " + e.getMessage());
		}
	}
	@At("/role/removeRP")
	@Ok("json")
	public Res removeRP(int roleId, String permission){
		try{
			String[] ps = permission.split("-");
			int[] pids = new int[ps.length];
			for(int i = 0; i < ps.length; i ++){
				pids[i] = Integer.parseInt(ps[i]);
			}
			return Res.NEW().code(Res.SUCCESS).msg("删除了" + roleService.removePermission(roleId, pids) + "条记录");
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("删除异常: " + e.getMessage());
		}
	}
	@At("/role/update")
	@Ok("json")
	public Res updateRole(@Param("..")Role role){
		try{
			role.setUpdateTime(new Date());
			if(dao.updateIgnoreNull(role) > 0){
				return Res.NEW().code(Res.SUCCESS).msg("更新角色成功");
			}else{
				return Res.NEW().code(Res.ERROR).msg("更新角色失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("更新权限异常: " + e.getMessage());
		}
	}
	
	/**
	 * 根据ID删除角色
	 * @param id
	 * @return
	 */
	@At("/role/delete")
	@Ok("json")
	public Res deleteRole(int id){
		try{
			int sum =roleService.delete(id);
			return Res.NEW().code(Res.SUCCESS).msg("删除" + sum + "条角色");
		}catch(Exception e){
			e.printStackTrace();
			return Res.NEW().code(Res.ERROR).msg("删除角色异常: " + e.getMessage());
		}
	}
}
